package com.zzb.framework.user.service;

import com.alibaba.fastjson.JSON;
import com.zzb.framework.role.entity.IUser;
import com.zzb.framework.role.service.SysMenuService;
import com.zzb.framework.role.vo.SysMenuTreeVO;
import com.zzb.framework.role.vo.UserLoginVo;
import com.zzb.framework.user.dao.UserDAO;
import com.zzb.framework.user.entity.User;
import com.zzb.framework.user.event.msg.LoginSuccessEvent;
import com.zzb.framework.user.form.UserLoginForm;
import com.zzb.framework.user.form.UserSearchForm;
import com.zzb.framework.common.*;
import com.zzb.framework.event.EventHome;
import com.zzb.framework.role.entity.SysRole;
import com.zzb.framework.role.service.SysRoleService;
import com.zzb.framework.role.service.SysRoleUserService;
import com.zzb.framework.user.vo.UserRoleVO;
import com.zzb.framework.utils.BeanUtils;
import com.zzb.framework.utils.Misc;
import com.zzb.framework.validator.annotation.ValidatorEnabled;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户账号 service类
 */
@Service
public class UserService extends BaseService<UserDAO, User> {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleUserService sysRoleUserService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDAO getDAO() {
        return userDAO;
    }

    public BasePage<UserRoleVO> queryUserVOPage(UserSearchForm userSearchForm) {
        BasePage<User> userBasePage = queryPage(userSearchForm);
        List<UserRoleVO> userRoleVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userBasePage.getContent())) {
            for (User user : userBasePage.getContent()) {
                UserRoleVO userRoleVO = new UserRoleVO();
                BeanUtils.copyProperties(user, userRoleVO);
                userRoleVO.setSysRoleList(sysRoleService.findByUserId(user.getId()));
                userRoleVOS.add(userRoleVO);
            }
        }
        return new BasePage<>(userRoleVOS, userBasePage.getPage(), userBasePage.getPageSize(), userBasePage.getTotalElements());
    }

    @ValidatorEnabled
    public BaseResponse<User> saveUser(User user, IUser operator) throws ServiceException {
        logger.info("正在保存用户[" + JSON.toJSONString(user) + "][" + JSON.toJSONString(operator) + "]");

        if (StringUtils.isEmpty(user.getId()) && findByLoginName(user.getLoginName()) != null) {
            return new BaseResponse<>(BaseResponse.FAIL, "保存用户失败，用户名不能重复");
        }
        user.setPassword(Misc.generatePassword(user.getPassword()));
        BaseResponse<User> createRet = insertOrUpdate(user, operator);
        return createRet;
    }

    public BaseResponse<UserLoginVo> login(UserLoginForm userLoginForm, String ip) {
        try {
            User user = getDAO().getByLoginNameAndPassword(userLoginForm.getLoginName(), userLoginForm.getPassword());
            UserLoginVo userLoginVo = new UserLoginVo();
            BeanUtils.copyProperties(user, userLoginVo);
            List<SysRole> sysRoles = sysRoleService.findByUserId(user.getId());
            userLoginVo.setRoleCodes(sysRoles);
            SysMenuTreeVO sysMenuTreeVO = sysMenuService.getTreeVoByUserId(user.getId());
            userLoginVo.setSysMenuTreeVO(sysMenuTreeVO);

            if (user.getActivate() != 1) {
                return new BaseResponse<>(BaseResponse.FAIL, "登录失败，该用户已被屏蔽", userLoginVo);
            }

            //登陆成功发布事件
            EventHome.publishEvent(new LoginSuccessEvent(user, ip, new Date()));
            return new BaseResponse<>(BaseResponse.SUCCESS, "登录成功", userLoginVo);
        } catch (DAOException e) {
            return new BaseResponse<>(BaseResponse.FAIL, e.getMessage());
        }
    }

    public BaseResponse deleteUser(String id, IUser operate) throws ServiceException {
        //删除用户权限
        sysRoleUserService.deleteByUserId(id);
        return deleteById(id);
    }

    public User findByLoginName(String name) {
        List<User> userList = userDAO.findByLoginName(name);
        if (CollectionUtils.isNotEmpty(userList)) return userList.get(0);
        return null;
    }

    public List<User> selectAll() {
        return getDAO().selectAll();
    }

}
